import * as types from '../../../global/constants/ActionTypes';
import UserDao from "../UserDao";
import Global from '../../../global/Global';

let user = {
  "name": "小明",
  "gender": "male",
  "age": 21
};
export function checkHasLogin() {
  return dispatch => {
    dispatch(checkingLogin());
    console.log('checkHasLogin start');
    UserDao.fetch().then(user => {
      if (user && user.name) {
        console.log('用户已经登录：' + user.name);
        dispatch(hasLogin(user));
        Global.user = user;
      } else {
        dispatch(loginFail("用户未登录"));
      }
    }).catch(err => {
      console.log("UserDao.fetch() err " + err);
      dispatch(loginFail("用户未登录 exception"));
    });
  }
}
export function login() {
  return dispatch => {
    dispatch(isLoginOnGoing());
    setTimeout(() => {
      fetch('https://www.baidu.com').then((res) => {
        UserDao.save(user);
        Global.user = user;
        dispatch(loginSuccess(user));
      }).catch((e) => {
        dispatch(loginFail("用户名或密码错误"));
      })
    }, 1000)
  }
}
//---------------------------检查登录--------------------------
function checkingLogin() {
  return {
    type: types.LOGIN_CHECKING_LOGIN,
    loading: true,
  }
}
function hasLogin(user) {
  return {
    type: types.LOGIN_HAS_LOGIN,
    loading: false,
    hasLogin: true,
    user: user,
  }
}
//---------------------------网络登录--------------------------

function isLoginOnGoing() {
  return {
    type: types.LOGIN_PROCESSING,
    loading: true,
  }
}

function loginSuccess(c) {
  return {
    type: types.LOGIN_SUCCESS,
    user: user,
    loading: false,
    isSuccess: true,
  }
}
//---------------------------通用--------------------------
function loginFail(errorMsg) {
  return {
    type: types.LOGIN_FAIL,
    loading: false,
    hasLogin: false,
    errorMessage: errorMsg,
    isSuccess: false,
  }
}